package com.lecoboy.highconcurrency.threaddemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * CAS实现原子操作
 */
public class CasAutomicCounter {
    //原子操作
    private AtomicInteger atomicI = new AtomicInteger(0);
    //线程不安全的变量
    private int i = 0;

    public static void main(String[] args) {
        final CasAutomicCounter cas = new CasAutomicCounter();
        List<Thread> ts = new ArrayList<Thread>(600);
        long start = System.currentTimeMillis();
        for (int j = 0; j < 100; j++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10000; i++) {
                        cas.safeCount();
                        cas.noSafecount();
                    }
                }
            });
            ts.add(t);
        }
        //循环启动线程
        for (Thread t : ts) {
            t.start();
        }
        //等待所有线程执行完成
        for (Thread t : ts) {
            try {
                //主线程等待完成后才能执行
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("非线程安全变量:" + cas.i);
        System.out.println("线程安全计数器：" + cas.atomicI);
        System.out.println("耗时:" + (System.currentTimeMillis() - start) + "ms");
    }

    /**
     * 自旋CAS实现线程安全计数器
     */
    private void safeCount() {
        for (; ; ) {
            //自旋 加成功即break
            int i = atomicI.get();
            boolean suc = atomicI.compareAndSet(i, ++i);
            if (suc) {
                break;
            }
        }
    }

    /**
     * 非线程安全计数器
     */
    private void noSafecount() {
        i++;
    }

}
